package com.randi.common.utils.token;

import com.randi.common.config.AppConfig;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

/**
 * @author ziye
 */
@Component
public class JwtTokenUtils {

    private static String TOKEN_KEY;
    private static Integer TOKEN_TIME;

    @Resource
    private void init(AppConfig.TokenConfig tokenConfig) {
        TOKEN_KEY = tokenConfig.getKey();
        TOKEN_TIME = tokenConfig.getAccess().getExpireTime();
    }

    /**
     * token 创建
     *
     * @param claim data
     * @return token
     */
    public static String createToken(HashMap<String, Object> claim) {
        return createToken(claim, TOKEN_TIME);
    }

    /**
     * token 创建
     *
     * @param claim   data
     * @param seconds 过期时间
     * @return token
     */
    public static String createToken(HashMap<String, Object> claim, Integer seconds) {
        long timeMillis = System.currentTimeMillis();

        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, TOKEN_KEY)
                .setClaims(claim)
                .setIssuedAt(new Date(timeMillis))
                .setExpiration(new Date(timeMillis + seconds * 1000));

        return jwtBuilder.compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    public static Claims checkToken(String token) {
        try {
            return Jwts.parser().setSigningKey(TOKEN_KEY).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取token过期时间
     *
     * @param token token
     * @return 过期时间(秒) 0：已过期
     */
    public static long getTokenExpired(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(TOKEN_KEY)
                    .parseClaimsJws(token)
                    .getBody();
            Date expiration = claims.getExpiration();
            long time = expiration.getTime() - (new Date().getTime());
            return time / 1000;
        } catch (ExpiredJwtException e) {
            return 0;
        }
    }

    /**
     * token 续期
     *
     * @param token token
     * @return tokenRefresh
     */
    public static String tokenRefresh(String token) {
        token = token.split(" ")[1];

        Claims claims = Jwts.parser()
                .setSigningKey(TOKEN_KEY)
                .parseClaimsJws(token)
                .getBody();

        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, TOKEN_KEY)
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 1000));
        return jwtBuilder.compact();
    }


}
